﻿namespace Collaboris.Saf.Converters.Spring
{
    using System;

    using Definitions;

    using Utils;

    public class SerializableStringDictionaryConverter : SafConverter<SerializableStringDictionary>
    {
        public override string Convert(SerializableStringDictionary source, bool renderAsTemplate, string propertyName)
        {
            ValidationHelper.VerifyStringArgument(propertyName, "propertyName");
            ValidationHelper.VerifyObjectArgument(source, "source");
            
            string springXml = string.Empty;
            springXml += @"<property name=""" + propertyName + @""">";
            springXml += @" <object type=""SafDictionary"">";
            springXml += @"  <constructor-arg name=""dictionary"">";
			springXml += @"   <dictionary>";

            foreach (string key in source.Keys)
            {
                if (renderAsTemplate)
                    springXml += @"<entry key=""" + key + @""" expression=""Func.Eval('${" + key.ToLower() + @"}')"" />";
                else
                    springXml += @"<entry key=""" + key + @""" value=""" + source[key] + @""" />";
            }
            
			springXml += @"   </dictionary>";
			springXml += @"  </constructor-arg>";
            springXml += @" </object>";
            springXml += @"</property>";

            return springXml;
        }

        public override string Convert(SafPropertyDefinition propertyDefinition, bool renderAsTemplate)
        {
            base.Convert(propertyDefinition, renderAsTemplate);

            string springXml = string.Empty;
            if (renderAsTemplate)
            {
                springXml += @"<property name=""" + propertyDefinition.Name + @""" expression=""" +
              @"Func.Eval('${" + propertyDefinition.ParentedName.ToLower() + @"}')" + @"""/>";
            }
            else
            {
                springXml += @"<property name=""" + propertyDefinition.Name + @""">";
                springXml += @"<object type=""SafDictionary"">";
                springXml += @" <constructor-arg name=""dictionary"">";

                springXml += propertyDefinition.Example;

                springXml += @" </constructor-arg>";
                springXml += @"</object>";
                springXml += @"</property>";
            }
            return springXml;
        }
    }
}
